package be.jabapage.snooker.service.competition.impl;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import org.apache.commons.lang.Validate;

import be.jabapage.snooker.exception.EntityNotFoundException;
import be.jabapage.snooker.jdo.competition.CompetitionGamePlayer;
import be.jabapage.snooker.service.competition.api.ICompetitionGamePlayerService;


public class AppEngineCompetitionGamePlayerService implements ICompetitionGamePlayerService, Serializable {

	private static final long serialVersionUID = -9017842638841978034L;
	private final PersistenceManagerFactory pmf;

	public AppEngineCompetitionGamePlayerService(final PersistenceManagerFactory pmf) {
		Validate.notNull(pmf,"The persistence Manager factory cannot be null");
		this.pmf = pmf;
	}

	/**
	 * {@inheritDoc}
	 */
	public void store(final CompetitionGamePlayer competitionGamePlayer) {
		Validate.notNull(competitionGamePlayer);
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			pm.makePersistent(competitionGamePlayer);
		} finally {
			pm.close();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public CompetitionGamePlayer retrieve(final Long key) throws EntityNotFoundException {
		Validate.notNull(key, "A key should be provided.");
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			CompetitionGamePlayer objectById = pm.getObjectById(CompetitionGamePlayer.class, key);
			if (objectById == null) {
				throw new EntityNotFoundException();
			}
			return objectById;
		} finally {
			pm.close();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public Set<CompetitionGamePlayer> retrieveForCompetitionGame(final Long competitionGameId) {
		Validate.notNull(competitionGameId);
		PersistenceManager pm = pmf.getPersistenceManager();
		Set<CompetitionGamePlayer> resultSet = new HashSet<CompetitionGamePlayer>();
		Query query = pm.newQuery(CompetitionGamePlayer.class);
		try {
			query.setFilter("competitionGameId == competitionGameParam");
			query.declareParameters("Long competitionGameParam");
			@SuppressWarnings("unchecked")
			List<CompetitionGamePlayer> result = (List<CompetitionGamePlayer>) query.execute(competitionGameId);
			if (result != null) {
				resultSet.addAll(result);
			}
		} finally {
			query.closeAll();
			pm.close();
		}
		return resultSet;
	}

	public void delete(final Long key) throws EntityNotFoundException {
		Validate.notNull(key, "We cannot delete an instance withour a key.");
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			CompetitionGamePlayer dataInstance = pm.getObjectById(CompetitionGamePlayer.class, key);
			if (dataInstance == null) {
				throw new EntityNotFoundException();
			}

			pm.deletePersistent(dataInstance);
		} finally {
			pm.close();
		}
	}


}
